package com.tensquare.manager.filter;

import cn.hutool.core.util.StrUtil;
import com.netflix.discovery.converters.Auto;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.tensquare.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.http.protocol.RequestContent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by WF on 2020/12/24 15:12
 */
@Component
public class ManagerZuulFilter extends ZuulFilter {
    @Autowired
    private JwtUtil jwtUtil;
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    //1.执行的代码
    @Override
    public Object run() throws ZuulException {
        //1.1)得到请求对象
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        //1.2)排除特殊情况的放行
        if(request.getMethod().equals("OPTIONS")){
            return null;
        }
        if(request.getRequestURL().toString().contains("/login")){
            return null;
        }
        //1.3)得到请求头
        String header = request.getHeader("Authorization");
        //1.4)判断是否以Bear 开头
        if(StrUtil.isNotBlank(header) && header.startsWith("Bearer ")){
            String token = header.substring(7);
            //1.5)解析请求头
            Claims claims = jwtUtil.parseJwt(token);
            //1.6)如果存在，找到角色名
            if(claims != null ){
                String role = (String) claims.get("role");
                if("admin".equals(role)){
                    currentContext.addZuulRequestHeader("Authorization",header);
                    return null;
                }

            }
        }

        //1.7)阻止继续执行
        currentContext.setSendZuulResponse(false);  //不再发送响应
        currentContext.setResponseStatusCode(403);  //响应状态码为403
        currentContext.setResponseBody("无权访问！"); //设置响应体内容
        currentContext.getResponse().setContentType("text/html;charset=utf-8"); //设置内容类型

        return null;
    }
}
